package com.dfish.downloadtool;

import java.lang.reflect.Method;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.internal.telephony.ITelephony;

public class MainActivity extends Activity implements View.OnClickListener {
    private MyService mService;
    private boolean mIsServiceBinded;
    private String mPhoneNum;
    private Button mButtonsetupRtsp;
    private Button mButtonStopRtsp;
    private EditText mTotalDataEditText;
    private TextView rtspResultView;
    private EditText mThreadNumber;
    private TextView mPhoneNumberTextView;
    private EditText mDownloadTimeEditText;
    
    private static final int START_THREAD = 0;
    private static final int CACULATE_DATA = 1;
    private static final int HAND_OFF = 2;
    private static final int USE_TIME = 3;
    
    public static final String RTSP_NAME = "rstp";
    public static final String RTSP_TOTAL = "rtsp_total";
    public static final String DOWNLOAD_TIME = "download_time";
    public static final String STOP_MUSIC = "stop_music";
    public static final String TOTAL_TIME = "total_time";
    
    public static long mDownloadData;
    public static byte[]lock = new byte[0];
    private ITelephony iTelephony;
    private TelephonyManager manager;
    private int mUrlPoint = 0;
    private IntentFilter intentFilter;
    private boolean isRegister = false;
    
    private static int mDownloadTime = 0;
    
    private static int mTotalTime;
    private TextView mUseTimeTextView;
    
    private static String mTotalDataString; //阀值总量
    public static long mMaxData = -1L;
    public static boolean isRunning = false;
    
    private BroadcastReceiver mTimeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_TIME_TICK.equals(action)) {
                mDownloadTime = readIntPreferences(RTSP_NAME, DOWNLOAD_TIME);
                if (mDownloadTime >= mTotalTime) {
                    isRunning = false;
                    mService.closeRtsp();
                    mService.gameOver();
                    if (isRegister) {
                        unregisterReceiver(mTimeReceiver);
                        isRegister = false;
                    }
                } else {
                    mDownloadTime++;
                    writeIntPreferences(RTSP_NAME, DOWNLOAD_TIME, mDownloadTime);
                    handler.sendEmptyMessage(USE_TIME);
                }
            }
        }
    };
    
    private static final String[] sUrlList = {
        "rtsp://vod01.v.vnet.mobi/00000018/20120918/10140000000180000000018892443001/00000018_10140000000180000000018892460001_150MP4QVGA.3gp",
        "rtsp://vod01.v.vnet.mobi/00000018/20120920/10142000000180000000018972880001/00000018_10142000000180000000018972894001_150MP4QVGA.3gp",
        "rtsp://vod01.v.vnet.mobi/00000018/20120920/10142000000180000000018972881001/00000018_10142000000180000000018972896001_150MP4QVGA.3gp",
        "rtsp://vod01.v.vnet.mobi/00000018/20120920/10142000000180000000018972882001/00000018_10142000000180000000018972898001_150MP4QVGA.3gp",
        "rtsp://vod01.v.vnet.mobi/00000097/20120926/10145000000970000000019132893001/00000097_10145000000970000000019132982001_150MP4QVGA.3gp",
        "rtsp://vod01.v.vnet.mobi/00000097/20120926/10145000000970000000019132894001/00000097_10145000000970000000019132984001_150MP4QVGA.3gp",
        "rtsp://vod01.v.vnet.mobi/00000097/20120926/10145000000970000000019132895001/00000097_10145000000970000000019132986001_150MP4QVGA.3gp",
        "rtsp://vod01.v.vnet.mobi/00000018/20120918/10140000000180000000018892441001/00000018_10140000000180000000018892456001_150MP4QVGA.3gp",
        "rtsp://vod01.v.vnet.mobi/00000018/20120918/10140000000180000000018892442001/00000018_10140000000180000000018892458001_150MP4QVGA.3gp",
        "rtsp://vod01.v.vnet.mobi/00000018/20120918/10140000000180000000018892443001/00000018_10140000000180000000018892460001_150MP4QVGA.3gp"
    };
    
    public void phoner() {
        manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        Class<TelephonyManager> c = TelephonyManager.class;
        Method getITelephonyMethod = null;
        try {
            getITelephonyMethod = c.getDeclaredMethod("getITelephony",
                    (Class[]) null);
            getITelephonyMethod.setAccessible(true);
            iTelephony = (ITelephony) getITelephonyMethod.invoke(manager,
                    (Object[]) null);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDownloadData = readLongPreferences(RTSP_NAME, RTSP_TOTAL);
        setContentView(R.layout.activity_main);
        TelephonyManager mTelephonyMgr;
        mTelephonyMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
        mPhoneNum = mTelephonyMgr.getLine1Number();
        DDebug.logd("mPhoneNum = " + mPhoneNum);

        mButtonStopRtsp = (Button) findViewById(R.id.rtsp_stop);
        mButtonStopRtsp.setOnClickListener(this);
        rtspResultView = (TextView) findViewById(R.id.rtsp_resultView);
        mThreadNumber = (EditText) findViewById(R.id.threads_num);
        mThreadNumber.setText("30");
        ((Button) findViewById(R.id.clear_record)).setOnClickListener(this);
        ((Button) findViewById(R.id.stop_music)).setOnClickListener(this);
        mButtonsetupRtsp = (Button) findViewById(R.id.rtsp_setup);
        mButtonsetupRtsp.setOnClickListener(this);
        mPhoneNumberTextView = (TextView) this.findViewById(R.id.phone_number);
        mTotalDataEditText = (EditText) findViewById(R.id.total_data);
        mTotalDataEditText.setText("1000");
        mDownloadTimeEditText = (EditText)findViewById(R.id.download_time);
        ((Button) findViewById(R.id.dial_number)).setOnClickListener(this);
        mUseTimeTextView = (TextView) findViewById(R.id.use_time);
        
        phoner();
        
        intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        setResultView(mDownloadData);
        handler.sendEmptyMessageDelayed(CACULATE_DATA, 2000);
    }
    
    private void setResultView(long data) {
        long mm = data/1048576;
        long mmy = data%1048576;
        long kk = mmy/1024;
        long bb = mmy%1024;
        rtspResultView.setText("当前下载量为"+ mPhoneNum +":" + mm + "M" + kk + "K" + bb + "B");
    }

    public void onStart() {
        super.onStart();

        if (null == startService(new Intent(MainActivity.this, MyService.class))) {
            return;
        }
        mIsServiceBinded = bindService(new Intent(MainActivity.this,
                MyService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
        if (!mIsServiceBinded) {
            finish();
            return;
        }
    }

    public void onResume() {
        super.onResume();
    }
    
    public void onPause() {
        super.onPause();
    }
    
    public void onStop() {
        mService.closeRtsp();
        if (mIsServiceBinded) {
            unbindService(mServiceConnection);
            mIsServiceBinded = false;
        }
        super.onStop();
    }

    private void writeLongPreferences(String perferencesName, String key, long value) {
        SharedPreferences preferences = getSharedPreferences(perferencesName,0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putLong(key, value).commit();
    }
    
    private void writeIntPreferences(String perferencesName, String key, int value) {
        SharedPreferences preferences = getSharedPreferences(perferencesName,0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt(key, value).commit();
    }
    
    private void writeBooleanPreferences(String perferencesName, String key, Boolean value) {
        SharedPreferences preferences = getSharedPreferences(perferencesName,0);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putBoolean(key, value).commit();
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            DDebug.logd("mService");
            mService = ((MyService.MyBinder) service).getService();
        }

        public void onServiceDisconnected(ComponentName className) {
            DDebug.logd("mService is null");
            mService = null;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        
        if (isRegister) {
            unregisterReceiver(mTimeReceiver);
            isRegister = false;
        }
    }

    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
        case R.id.rtsp_setup:
            isRunning = true;
            writeBooleanPreferences(RTSP_NAME, STOP_MUSIC, false);
            if (checkNetWork(this)) {
                handler.sendEmptyMessage(START_THREAD);
                mButtonsetupRtsp.setEnabled(false);
                mTotalDataEditText.setEnabled(false);
                mThreadNumber.setEnabled(false);
                mDownloadTimeEditText.setEnabled(false);
            } else {
                Toast.makeText(MainActivity.this, "请打开网络链接后重试！",
                        Toast.LENGTH_SHORT).show();
            }
            
            String time = mDownloadTimeEditText.getText().toString().trim();
            if (!TextUtils.isEmpty(time)) {
                mTotalTime = Integer.parseInt(time);
                registerReceiver(mTimeReceiver, intentFilter);
                isRegister = true;
                mDownloadTime = readIntPreferences(RTSP_NAME, DOWNLOAD_TIME);
                mUseTimeTextView.setText(" 已下载：" + mDownloadTime + "分钟");
            }
            
            handler.sendEmptyMessage(USE_TIME);
            break;
        case R.id.rtsp_stop:
            isRunning = false;
            mService.closeRtsp();
            mButtonsetupRtsp.setEnabled(true);
            if (isRegister) {
                unregisterReceiver(mTimeReceiver);
                isRegister = false;
            }
            break;
        case R.id.clear_record:
            // 程序正在跑的时候不能清除数据
            if (!isRunning) {
                DDebug.logd("clear data");
                mDownloadData = 0;
                writeLongPreferences(MainActivity.RTSP_NAME, MainActivity.RTSP_TOTAL, 0L);
                mDownloadTime = 0;
                mTotalTime = 0;
                writeBooleanPreferences(RTSP_NAME, STOP_MUSIC, false);
                writeIntPreferences(RTSP_NAME, DOWNLOAD_TIME, 0);
                
                if (!mTotalDataEditText.isEnabled()) {
                    mTotalDataEditText.setEnabled(true);
                }
                
                if (!mThreadNumber.isEnabled()) {
                    mThreadNumber.setEnabled(true);
                }
                
                if (!mDownloadTimeEditText.isEnabled()) {
                    mDownloadTimeEditText.setEnabled(true);
                }
            }
            break;
        case R.id.stop_music:
            DDebug.logd("stop music");
            mService.stopPlaying();
            writeBooleanPreferences(RTSP_NAME, STOP_MUSIC, true);
            break;
        case R.id.dial_number:
            String phoneNumber = mPhoneNumberTextView.getText().toString();
            if (!TextUtils.isEmpty(phoneNumber)) {
                Uri localUri = Uri.parse("tel:" + phoneNumber);
                Intent call = new Intent(Intent.ACTION_CALL, localUri);
                call.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(call);
            }
            handler.sendEmptyMessageDelayed(HAND_OFF, 45 * 1000);
            break;
        }
    }
    
    public static boolean checkNetWork(Context con) {
        ConnectivityManager connMgr = null;
        if (null == connMgr) {
            connMgr = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
        }
        NetworkInfo mobileInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobileInfo.isAvailable()) {
            return true;
        } else {
            return false;
        }
    }
    
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case START_THREAD:
                mService.closeRtsp();
                String text = mThreadNumber.getText().toString().trim();
                mTotalDataString = mTotalDataEditText.getText().toString().trim();
                if (!TextUtils.isEmpty(text) && !TextUtils.isEmpty(mTotalDataString)) {
                    if (isRunning) {
                        mMaxData = Long.parseLong(mTotalDataString) * 1048576;
                        mService.setupRtsp(
                                sUrlList[mUrlPoint],
                                Integer.parseInt(mThreadNumber.getText().toString()));
                        mUrlPoint = (mUrlPoint + 1) % sUrlList.length;
                        handler.sendMessageDelayed(handler.obtainMessage(), 3 * 60 * 1000);
                    }
                } else {
                    Toast.makeText(MainActivity.this, "请输入正确的线程数或者下载总量！",
                            Toast.LENGTH_SHORT).show();
                }
                break;
            case CACULATE_DATA:
                setResultView(mDownloadData);
                handler.sendEmptyMessageDelayed(CACULATE_DATA, 1000);
                break;
            case HAND_OFF:
                try {
                    iTelephony.endCall();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                
                break;
            case USE_TIME:
                mUseTimeTextView.setText(" 已下载：" + mDownloadTime + "分钟");
                break;
            }
        }
    };

    private long readLongPreferences(String perferencesName, String key) {
        SharedPreferences preferences = getSharedPreferences(perferencesName, MODE_PRIVATE);
        long result = preferences.getLong(key, 0);
        return result;
    }
    
    private int readIntPreferences(String perferencesName, String key) {
        SharedPreferences preferences = getSharedPreferences(perferencesName, MODE_PRIVATE);
        int result = preferences.getInt(key, 0);
        return result;
    }
    
    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        if(keyCode == KeyEvent.KEYCODE_BACK) {  
            new AlertDialog.Builder(this)  
            .setIcon(android.R.drawable.ic_dialog_alert)  
            .setTitle("退出")  
            .setMessage("是否要退出程序?")  
            .setPositiveButton("是", new DialogInterface.OnClickListener() {  
                @Override  
                public void onClick(DialogInterface dialog, int which) {
                    DDebug.logd("back yes");
                    isRunning = false;
                    mService.closeRtsp();
                    if (isRegister) {
                        unregisterReceiver(mTimeReceiver);
                        isRegister = false;
                    }
                    MainActivity.this.finish();      
                }  
            })  
            .setNegativeButton("否", null)  
            .show();  
            return true;  
        }  
        else {  
            return super.onKeyDown(keyCode, event);  
        }  
    }  
}
